package com.tzbank.wisdom.utils;

import com.dcfs.esb.ftp.client.FtpGet;
import com.dcfs.esb.ftp.server.error.FtpException;
import com.tzbank.esb.util.FtpClientConfigs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ESBFileDownloadUtil {



    public static void downloadFile(String fileName, String localFilePath, Environment environment) {
        FtpClientConfigs.loadConf(environment);
        //下载文件
        log.info("remoteFile{}:" + "/COREBANK/CREDITCARD/" + fileName);
        log.info("localFilePath{}:" + localFilePath);
        FtpGet ftp = null;
        try {
            ftp = new FtpGet("/COREBANK/CREDITCARD/" + fileName, localFilePath, true);
            ftp.doGetFile();
        } catch (FtpException e) {
            if (log.isErrorEnabled()) {
                log.error("文件下载出错", e);
            }
        } finally {
            if (ftp != null)
                ftp.close();
        }

    }


    public static List readFile(String url, String[] index) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        List<Map<String, String>> list = new ArrayList<>();
        File file = new File(url);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "GBK");
            BufferedReader br = new BufferedReader(inputStreamReader);
            String s = null;
            while ((s = br.readLine()) != null) {
                // System.out.println(s.toString());
                Map<String, String> map = new HashMap<>();
                String[] split = s.split("\\|");
                for (int i = 0; i < split.length; i++) {
                    map.put(index[i] + "", split[i].replace(" ", ""));
                }
                list.add(map);
                stringBuilder.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }
}
